<?php

/* 
 *  用户模型
 */
class User_model extends CI_Model {
    
    const TN = "users";
    
    /**
     * 添加用户时生成的用户名
     * @var type 
     */
    private $_u_name;
    
    /**
     * 
     * @param type $id
     * @return array
     */
    public function get($id) {
        $query = $this->db->get_where(self::TN, array('u_id' => $id));
        
        return $query->first_row("array");
    }
    
    public function get_by_name($name) {
        $query = $this->db->get_where(self::TN, array('u_name' => $name));
        
        return $query->first_row("array");
    }

        public function new_user() {
        return array(
            'u_name' => '保存时自动生成',
            'u_password' => '',
            'u_password_again' => '',
            'u_first_date' => date('Y-m-d'),
            'u_last_date' => (date('Y') + 10) . '-12-31',
            'u_real_name' => '',
            'u_sex' => '',
            'u_telephone' => '',
        );
    }
    
    public function insert($user) {
        $user['u_name'] = $this->_get_new_u_name(); // 用户名自动生成
        $user['u_password'] = $this->_encrypt_password($user['u_password'], $user['u_salt']);
        $this->db->insert(self::TN, $user);
        $this->_u_name = $user['u_name'];
    }

    public function insert_id() {
        return $this->db->insert_id();
    }
    
    public function u_name() {
        return $this->_u_name;
    }


    public function update($id, $user) {
        if ($user['u_password'] != '') {
            $user['u_password'] = $this->_encrypt_password($user['u_password'], $user['u_salt']);
        } else {
            /* 密码为空，不更新密码和密码盐 */
            unset($user['u_password']);
            unset($user['u_salt']);
        }
        unset($user['u_name']); // 用户名不能修改

        $this->db->where('u_id', $id);
        $this->db->update(self::TN, $user);
    }
    
    public function delete($id) {
        $this->db->delete(self::TN, array('u_id' => $id));
    }
    
    /**
     * 取当前有效的有财务组权限的人员
     * @param $financial_uids 有财务组权限的uid数组
     */
    public function fetch_financial_users($financial_uids) {
        return $this->fetch_array(array(
            'uids' => $financial_uids,
            'active' => true,
        ));
    }
    
    /**
     * 
     * @param type $conditions
     * @param type $per_page 默认0表示取所有记录
     * @param type $page
     * @return array
     */
    public function fetch_array($conditions = array(), $per_page = 0, $page = 0) {
        $this->_set_where($conditions);
        if ($per_page > 0) {
            $offset = ($page - 1) * $per_page;
            $this->db->limit($per_page, $offset);
        }
        $this->db->order_by('u_id', 'desc');

        return $this->db->get(self::TN)->result_array();
    }
    
    /**
     * 返回记录总数
     * param $conditions
     */
    public function fetch_count($conditions) {
        $this->_set_where($conditions);
        $this->db->from(self::TN);
        
        return $this->db->count_all_results();
    }
    
    /**
     * 验证用户名和密码
     * @param type $u_name
     * @param type $u_password
     */
    public function validate($u_name, $u_password) {
        $user = $this->get_by_name($u_name);
        if (empty($user)) {
            return false;
        }
        
        $u_password = $this->_encrypt_password($u_password, $user['u_salt']);
        return $u_password == $user['u_password'];
    }
    
    /**
     * 设置where
     * @param type $conditions
     */
    private function _set_where($conditions) {
        if (isset($conditions['keyword']) && $conditions['keyword'] != '') {
            $this->db->like('u_name', $conditions['keyword']);
            $this->db->or_like('u_real_name', $conditions['keyword']);
        }
        
        /* 活跃的 */
        if (isset($conditions['active'])) {
            $today = date('Y-m-d');
            $this->db->where('u_first_date <=', $today);
            $this->db->where('u_last_date >=', $today);
        }
        
        /* 用户id数组 */
        if (isset($conditions['uids'])) {
            $this->db->where_in('u_id', $conditions['uids'] + array(0));
        }
    }
    
    /**
     * 取下一个用户名
     * 规则，三位数字，从001开始，自动增加
     */
    private function _get_new_u_name() {
        $this->db->select_max('u_name');
        $query = $this->db->get(self::TN);
        $row = $query->first_row('array');
        if (empty($row)) {
            return '001';
        } else {
            return str_pad(intval($row['u_name']) + 1, 3, '0', STR_PAD_LEFT);
        }
    }
    
    /**
     * 加密密码
     */
    private function _encrypt_password($password, $salt) {
        return md5(md5($password) . $salt);
    }
}

